package com.base.common.json;

import org.codehaus.jackson.map.ObjectMapper;

import java.io.StringWriter;
import java.text.SimpleDateFormat;

/**
 * json工具类
 * @author Kevin Colin
 */
public class JsonUtil
{
	private static final SimpleDateFormat dateFormate = 
			new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	/**
	 * 从java对象转换为字符串
	 * 注：DTO：data transition object数据传输对象
	 * @param dto
	 * @return String
	 */
	public static String dto2String(Object dto)
	{
		// ObjectMapper 线程安全具有缓存机制，重用可显著提高效率，实际使用中可设为全局公用
		ObjectMapper mapper = new ObjectMapper();		
//		dateFormate.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		mapper.setDateFormat(dateFormate);
		
		// 用此类构造字符串
		StringWriter w = new StringWriter();
		try
		{
			// writeXXX方法是将对象写成JSON
			mapper.writeValue(w, dto);
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		return w.toString();
	}
	
	/**
	 * 从字符串转换为java对象
	 * 注：DTO：data transition object数据传输对象
	 * @param jsonStr
	 * @return Object
	 */
	public static <T> T string2Obejct(String jsonStr,Class<T> c)
	{
		// ObjectMapper 线程安全具有缓存机制，重用可显著提高效率，实际使用中可设为全局公用
		ObjectMapper mapper = new ObjectMapper();
//		dateFormate.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		mapper.setDateFormat(dateFormate);
		
		T obj = null;
		try
		{
			// readXXX方法是将JSON封装成对象
			obj = mapper.readValue(jsonStr, c);
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		
		return obj;
	}
}
